﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using FusionAPI;
using System.Configuration;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace PFSync
{
    /// <summary>
    /// Summary description for OAuth
    /// </summary>
    public static class FusionToken
    {
        public static string GenerateRequestTokenUrl(string strConsumerKey, string strConsumerSecret, string strCallBackUrl)
        {
            try
            {
                Uri uri = new Uri(ConfigurationManager.AppSettings["FusionToken"]);
                string str_1 = "";
                string str_2 = "";
                PFOAuthBase PFoAuth = new PFOAuthBase();

                string nonce = PFoAuth.GenerateNonce();
                string timeStamp = PFoAuth.GenerateTimeStamp();
                string sig = PFoAuth.GenerateSignature(uri,
                    ConfigurationManager.AppSettings["FusionAPIUser"], ConfigurationManager.AppSettings["FusionAPIPassword"],
                    string.Empty, string.Empty,
                    "GET", timeStamp, nonce,
                    PFOAuthBase.SignatureTypes.PLAINTEXT, out str_1, out str_2);

                sig = HttpUtility.UrlEncode(sig);

                StringBuilder sb = new StringBuilder(uri.ToString());
                sb.AppendFormat("?oauth_consumer_key={0}&", ConfigurationManager.AppSettings["FusionAPIUser"]);
                sb.AppendFormat("oauth_callback={0}&", ConfigurationManager.AppSettings["AppLocation"]);
                sb.AppendFormat("oauth_nonce={0}&", nonce);
                sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
                sb.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT");
                sb.AppendFormat("oauth_version={0}&", "1.0");
                sb.AppendFormat("oauth_signature={0}", sig);
                return sb.ToString();
            }
            catch (Exception e)
            {
                return "";
            }
        }

        public static string GetOauthToken(string strRequestTokenUrl)
        {
            try
            {
                // Get HTML data 
                WebClient client = new WebClient();
                client.UseDefaultCredentials = true;
                ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);

                Stream data = client.OpenRead(strRequestTokenUrl);
                StreamReader reader = new StreamReader(data);
                string str = "";
                str = reader.ReadLine();
                string strToken = "";
                while (str != null)
                {
                    //Extract The Request Token
                    if (str.Contains("oauth_token="))
                    {
                        strToken = str.Substring(str.IndexOf("oauth_token=") + 12, str.IndexOf("&oauth_token_secret") - str.IndexOf("oauth_token") - 12);
                        break;
                    }
                    str = reader.ReadLine();
                }
                data.Close();
                return strToken;
            }
            catch (WebException exp)
            {
                return "";
            }
        }

        public static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
        {
            return true;
        } 
    }
}